//package com.wbk.lotterysystemgateway.filter;
//
//import cn.hutool.core.io.IoUtil;
//import com.alibaba.fastjson.JSONObject;
//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import com.coolgua.common.bean.ApiCode;
//import com.coolgua.common.bean.ApiResult;
//import com.coolgua.common.constant.ActivityConstant;
//import com.coolgua.common.constant.ChannelTypeConstant;
//import com.coolgua.common.constant.IntegralConstant;
//import com.coolgua.common.constant.RuleConstant;
//import com.coolgua.common.util.ImageUtil;
//import com.coolgua.config.CoolguaConfig;
//import com.coolgua.models.entity.*;
//import com.coolgua.service.*;
//import com.google.common.collect.Maps;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.lang3.StringUtils;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.cache.annotation.Cacheable;
//import org.springframework.http.HttpEntity;
//import org.springframework.http.ResponseEntity;
//import org.springframework.stereotype.Service;
//import org.springframework.util.LinkedMultiValueMap;
//import org.springframework.util.MultiValueMap;
//import org.springframework.web.client.RestTemplate;
//
//import javax.net.ssl.HttpsURLConnection;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.io.*;
//import java.net.URL;
//import java.util.*;
//
///*******************************************************************************
// * @project: ganlee
// * @package: com.coolgua.service.impl
// * @author: wbk
// * @created: 2021/1/5
// * @purpose:
// *
// * Copyright 2021 coolgua.com All rights reserved.
// ******************************************************************************/
//@Slf4j
//@Service
//public class WxServiceImpl implements WxService {
//
//    @Autowired
//    CoolguaConfig coolguaConfig;
//
//    @Autowired
//    RestTemplate restTemplate;
//
//    @Autowired
//    ChannelUseRecordService channelUseRecordService;
//
//    @Autowired
//    WxValidateUtil wxValidateUtil;
//
//    @Autowired
//    WxMessageUtil wxMessageUtil;
//
//    @Autowired
//    ImageUtil imageUtil;
//
//    @Autowired
//    FileService fileService;
//
//    @Autowired
//    UserInviteService userInviteService;
//
//    @Autowired
//    PublicPosterService publicPosterService;
//
//    @Autowired
//    IntegralRuleService integralRuleService;
//
//    @Autowired
//    IntegralExchangeService integralExchangeService;
//
//    @Autowired
//    UserOtherService userOtherService;
//
//    @Autowired
//    UserService userService;
//
//    @Override
//    public String getAccessToken() {
//        String url = coolguaConfig.getMp().getDomain().concat("/ganlee/patient-mgmt-sys/server/public/index.php?s=/wexin/get_token");
//        ResponseEntity<JSONObject> responseEntity = restTemplate.getForEntity(url, JSONObject.class);
//        JSONObject jsonObject = responseEntity.getBody();
//        assert jsonObject != null;
//        if (2000 != jsonObject.getIntValue("code")) {
//            log.error("accessToken获取失败");
//            return null;
//        }
//        return jsonObject.getJSONObject("data").getString("token");
//    }
//
//    @Cacheable(cacheNames = "MiniToken")
//    @Override
//    public String getToken() {
//        String appId = coolguaConfig.getMini().getAppId();
//        String appSecret = coolguaConfig.getMini().getAppSecret();
//        String tokenUrl = String.format(ACCESS_TOKEN_URL, appId, appSecret);
//        HashMap hashMap = restTemplate.getForEntity(tokenUrl, HashMap.class).getBody();
//        assert hashMap != null;
//        if (!hashMap.containsKey(ACCESS_TOKEN)) {
//            log.error("微信小程序参数不正确");
//            return null;
//        }
//        return (String) hashMap.get(ACCESS_TOKEN);
//    }
//
//    @Override
//    public String getMiniQrCodeUrl(String accessToken) {
//        return String.format(WX_MINI_QRCODE_URL, accessToken);
//    }
//
//    @Override
//    public String getPublicQrCodeUrl(String accessToken) {
//        return String.format(WX_PUBLIC_QRCODE_URL, accessToken);
//    }
//
//    @Override
//    public String validate(String signature, String timestamp, String nonce, String echostr) {
//        log.info("signature:" + signature + ",timestamp:" + timestamp + ",nonce:" + nonce + ",echostr:" + echostr);
//        // 公众号接入要求若校验成功，则原样返回echostr
//        return wxValidateUtil.checkSignature(signature, timestamp, nonce) ? echostr : null;
//    }
//
//    @Override
//    public String wxCallbackHandel(HttpServletRequest request, HttpServletResponse response) throws Exception {
//        JSONObject jsonObject = wxMessageUtil.parseXml(request);
//        log.info(jsonObject.toJSONString());
//        // 转发给php系统
//        String url = coolguaConfig.getMp().getDomain().concat("/ganlee/patient-mgmt-sys/server/public/index.php?s=/wexin/echostr");
//        String xml = wxMessageUtil.jsonToXml(jsonObject);
//        log.info(xml);
//        String result = null;
//        try {
//            ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, xml, String.class);
//            result = responseEntity.getBody();
//            log.info(result);
//        } catch (Exception e) {
//            log.error("转发抛异常", e);
//        }
//        String openId = jsonObject.getString("FromUserName");
//        String msgType = jsonObject.getString("MsgType");
//        // 处理事件推送
//        if (wxMessageUtil.REQ_MESSAGE_TYPE_EVENT.equals(msgType)) {
//            String event = jsonObject.getString("Event");
//            log.info(event);
//            if (wxMessageUtil.EVENT_TYPE_SUBSCRIBE.equalsIgnoreCase(event)) {
//                String eventKey = jsonObject.getString("EventKey");
//                String[] strings = eventKey.split("_");
//                String str = strings[strings.length - 1];
//                if (StringUtils.isNotBlank(str)) {
//                    if (str.startsWith("channel:")) {
//                        String[] strings1 = str.split(":");
//                        String channelCode = strings1[strings1.length - 1];
//                        QueryWrapper<ChannelUseRecord> qw = new QueryWrapper<>();
//                        qw.eq("open_id", openId).eq("type", ChannelTypeConstant.MP).last("limit 1");
//                        if (channelUseRecordService.count(qw) == 0) {
//                            ChannelUseRecord channelUseRecord = new ChannelUseRecord();
//                            channelUseRecord.setOpenId(openId);
//                            channelUseRecord.setChannelCode(channelCode);
//                            channelUseRecord.setScanTime(new Date());
//                            channelUseRecordService.save(channelUseRecord);
//                        }
//                    } else if (str.startsWith("userId:")) {
//                        QueryWrapper<PublicPoster> queryWrapper = new QueryWrapper<>();
//                        queryWrapper.last("limit 1");
//                        PublicPoster publicPoster = publicPosterService.getOne(queryWrapper);
//                        if (publicPoster != null) {
//                            publicPoster.setInviteNumber(publicPoster.getInviteNumber() + 1);
//                            publicPoster.setScanNumber(publicPoster.getScanNumber() + 1);
//                            publicPosterService.updateById(publicPoster);
//                        }
//                        String[] strings1 = str.split(":");
//                        int userId = Integer.parseInt(strings1[strings1.length - 1]);
//                        QueryWrapper<UserInvite> qw = new QueryWrapper<>();
//                        qw.eq("open_id", openId).last("limit 1");
//                        if (userInviteService.count(qw) == 0) {
//                            UserInvite userInvite = new UserInvite();
//                            userInvite.setUserId(userId);
//                            userInvite.setOpenId(openId);
//                            String uri = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=";
//                            ResponseEntity<JSONObject> responseEntity = restTemplate.getForEntity(uri.concat(getAccessToken()).concat("&openid=" + openId), JSONObject.class);
//                            JSONObject body = responseEntity.getBody();
//                            assert body != null;
//                            if (body.containsKey("errmsg")) {
//                                log.warn(body.getString("errmsg"));
//                            } else {
//                                userInvite.setNickname(body.getString("nickname"));
//                                userInvite.setSex(body.getIntValue("sex"));
//                                userInvite.setCity(body.getString("city"));
//                                userInvite.setProvince(body.getString("province"));
//                                userInvite.setCountry(body.getString("country"));
//                                userInvite.setHeadimgurl(fileService.uploadFromUrl(body.getString("headimgurl")));
//                                userInviteService.save(userInvite);
//                                QueryWrapper<IntegralRule> qw1 = new QueryWrapper<>();
//                                qw1.eq("integral_rule_key", RuleConstant.FORWARD_AND_SCAN).eq("status", 1).last("limit 1");
//                                IntegralRule integralRule = integralRuleService.getOne(qw1);
//                                if (integralRule == null) {
//                                    // 积分规则不存在或暂停使用
//                                    log.info("当前积分规则:" + RuleConstant.FORWARD_AND_SCAN + ",不存在或暂停使用");
//                                } else {
//                                    // 获取当前用户邀请方式已获得的总积分
//                                    QueryWrapper<IntegralExchange> qw2 = new QueryWrapper<>();
//                                    qw2.select("user_id", "type", "sum(integral) as integralTotal").eq("user_id", userId).groupBy("type").having("type = {0}", IntegralConstant.FORWARD_AND_SCAN);
//                                    IntegralExchange integral = integralExchangeService.getOne(qw2);
//                                    if (integral == null) {
//                                        // 增加积分获取记录
//                                        IntegralExchange integralExchange = new IntegralExchange();
//                                        integralExchange.setUserId(userId);
//                                        integralExchange.setType(IntegralConstant.FORWARD_AND_SCAN);
//                                        integralExchange.setIntegral(integralRule.getIntegral());
//                                        integralExchangeService.save(integralExchange);
//                                        // 更新已发放积分记录
//                                        integralRule.setIntegralGiveOut(integralRule.getIntegralGiveOut() + integralRule.getIntegral());
//                                        integralRuleService.updateById(integralRule);
//                                        // 修改用户总积分记录
//                                        QueryWrapper<UserOther> qw3 = new QueryWrapper<>();
//                                        qw3.eq("user_id", userId).last("limit 1");
//                                        UserOther userOther = userOtherService.getOne(qw3);
//                                        if (userOther == null) {
//                                            userOther = new UserOther(userId, integralRule.getIntegral(), null, null);
//                                            userOtherService.save(userOther);
//                                        } else {
//                                            userOther.setIntegral(userOther.getIntegral() + integralRule.getIntegral());
//                                            userOtherService.update(userOther, qw3);
//                                        }
//                                    }
//                                    if (integral != null) {
//                                        if (integralRule.getIntegralUpperLimit() != -1 && integral.getIntegralTotal() >= integralRule.getIntegralUpperLimit()) {
//                                            // 该积分的获取已达到上限
//                                            log.info("当前用户:" + userId + ",获取的积分类型:" + RuleConstant.FORWARD_AND_SCAN + "已达到上限");
//                                        } else {
//                                            // 增加积分获取记录
//                                            IntegralExchange integralExchange = new IntegralExchange();
//                                            integralExchange.setUserId(userId);
//                                            integralExchange.setType(IntegralConstant.FORWARD_AND_SCAN);
//                                            integralExchange.setIntegral(integralRule.getIntegral());
//                                            integralExchangeService.save(integralExchange);
//                                            // 更新已发放积分记录
//                                            integralRule.setIntegralGiveOut(integralRule.getIntegralGiveOut() + integralRule.getIntegral());
//                                            integralRuleService.updateById(integralRule);
//                                            // 修改用户总积分记录
//                                            QueryWrapper<UserOther> qw3 = new QueryWrapper<>();
//                                            qw3.eq("user_id", userId).last("limit 1");
//                                            UserOther userOther = userOtherService.getOne(qw3);
//                                            if (userOther == null) {
//                                                userOther = new UserOther(userId, integralRule.getIntegral(), null, null);
//                                                userOtherService.save(userOther);
//                                            } else {
//                                                userOther.setIntegral(userOther.getIntegral() + integralRule.getIntegral());
//                                                userOtherService.update(userOther, qw3);
//                                            }
//                                        }
//                                    }
//
//
//                                }
//                            }
//                        }
//                    }
//                }
//                int time = (int) (new Date().getTime() / 1000);
////                JSONObject media = putMedia(getMiniQrCode(openId), 1);
//                String qrCodeUrl = "https://ganlee-new.obs.cn-east-3.myhuaweicloud.com:443/20210428%2F88422037-aa88-4757-933b-5e4b415ab288.jpg";
//                JSONObject media = putMedia(qrCodeUrl, 1);
//                log.info(media.toJSONString());
//                result = "<xml>\n" +
//                        "  <ToUserName><![CDATA[" + openId + "]]></ToUserName>\n" +
//                        "  <FromUserName><![CDATA[" + coolguaConfig.getMp().getOriginalId() + "]]></FromUserName>\n" +
//                        "  <CreateTime>" + time + "</CreateTime>\n" +
//                        "  <MsgType><![CDATA[image]]></MsgType>\n" +
//                        "  <Image>\n" +
//                        "    <MediaId><![CDATA[" + media.getString("media_id") + "]]></MediaId>\n" +
//                        "  </Image>\n" +
//                        "</xml>";
//            } else if (wxMessageUtil.EVENT_TYPE_SCAN.equalsIgnoreCase(event)) {
//                String eventKey = jsonObject.getString("EventKey");
//                if (StringUtils.isNotBlank(eventKey)) {
//                    if (eventKey.startsWith("channel:")) {
//                        String[] strings1 = eventKey.split(":");
//                        String channelCode = strings1[strings1.length - 1];
//                        QueryWrapper<ChannelUseRecord> qw = new QueryWrapper<>();
//                        qw.eq("open_id", openId).last("limit 1");
//                        if (channelUseRecordService.count(qw) == 0) {
//                            ChannelUseRecord channelUseRecord = new ChannelUseRecord();
//                            channelUseRecord.setOpenId(openId);
//                            channelUseRecord.setChannelCode(channelCode);
//                            channelUseRecord.setScanTime(new Date());
//                            channelUseRecord.setType(0);
//                            channelUseRecordService.save(channelUseRecord);
//                        }
//                    } /*else if (eventKey.startsWith("userId:")) {
//                        QueryWrapper<PublicPoster> queryWrapper = new QueryWrapper<>();
//                        queryWrapper.last("limit 1");
//                        PublicPoster publicPoster = publicPosterService.getOne(queryWrapper);
//                        if (publicPoster != null) {
//                            publicPoster.setScanNumber(publicPoster.getScanNumber() + 1);
//                            publicPosterService.updateById(publicPoster);
//                        }
//                    }*/
//                }
//            }
//        }
//        log.info(result);
//        return result;
//    }
//
//    public static void main(String[] args) {
//
//        String result = "<xml>\n" +
//                "  <ToUserName><![CDATA[toUser]]></ToUserName>\n" +
//                "  <FromUserName><![CDATA[fromUser]]></FromUserName>\n" +
//                "  <CreateTime>12345678</CreateTime>\n" +
//                "  <MsgType><![CDATA[text]]></MsgType>\n" +
//                "  <Content><![CDATA[你好]]></Content>\n" +
//                "</xml>\n" +
//                " \n";
//
//        result = result +
//                " \n" +
//                "<xml>\n" +
//                "  <ToUserName><![CDATA[toUser]]></ToUserName>\n" +
//                "  <FromUserName><![CDATA[fromUser]]></FromUserName>\n" +
//                "  <CreateTime>12345678</CreateTime>\n" +
//                "  <MsgType><![CDATA[image]]></MsgType>\n" +
//                "  <Image>\n" +
//                "    <MediaId><![CDATA[image]]></MediaId>\n" +
//                "  </Image>\n" +
//                "</xml>";
//        System.out.println(result);
//    }
//
//    @Override
//    public void wxPublicNotify(String openId, String templateId, JSONObject jsonObject, String pagepath) {
//        JSONObject json = new JSONObject();
//        json.put("touser", openId);
//        json.put("template_id", templateId);
////        // 跳转到小程序指定页面
////        JSONObject json1 = new JSONObject();
////        json1.put("appid", "wx7c3d891c5b36c1d2");
////        json1.put("pagepath", pagepath);
////        json.put("miniprogram", json1);
//        json.put("data", jsonObject);
//        String accessToken = getAccessToken();
//        String url = PUBLIC_MESSAGE_SEND_URL.concat(accessToken);
//        ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, json, JSONObject.class);
//        JSONObject body = responseEntity.getBody();
//        assert body != null;
//        if (0 != body.getIntValue("errcode")) {
//            log.warn(body.getString("errmsg"));
//        }
//    }
//
//    @Override
//    public void wxMiniNotify(String openId, String templateId, JSONObject jsonObject) {
//        JSONObject json = new JSONObject();
//        json.put("touser", openId);
//        json.put("template_id", templateId);
////        // 跳转到小程序指定页面
////        json.put("page", "小程序页面路径");
////        json.put("miniprogram_state", "跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版");
//        json.put("data", jsonObject);
//        String accessToken = getToken();
//        String url = MINI_MESSAGE_SEND_URL.concat(accessToken);
//        ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, json, JSONObject.class);
//        JSONObject body = responseEntity.getBody();
//        assert body != null;
//        if (0 != body.getIntValue("errcode")) {
//            log.warn(body.getString("errmsg"));
//        }
//    }
//
//    @Override
//    public JSONObject putMedia(String stringUrl, Integer type) {
//        File file = imageUtil.getFileFromUrl(stringUrl);
//        String accessToken = null;
//        if (type == 0) {
//            accessToken = getToken();
//        } else if (type == 1) {
//            accessToken = getAccessToken();
//        }
//        String urlString = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=".concat(accessToken).concat("&type=image");
//        String result = null;
//        try {
//            URL url = new URL(urlString);
//            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
//            conn.setRequestMethod("POST");
//            conn.setDoInput(true);
//            conn.setDoOutput(true);
//            conn.setUseCaches(false);
//            conn.setRequestProperty("Connection", "Keep-Alive");
//            conn.setRequestProperty("Charset", "UTF-8");
//            // 设置边界
//            String BOUNDARY = "----------" + System.currentTimeMillis();
//            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
//            // 请求正文信息
//            // 第一部分
//            StringBuilder sb = new StringBuilder();
//            // 必须多两条道
//            sb.append("--");
//            sb.append(BOUNDARY);
//            sb.append("\r\n");
//            sb.append("Content-Disposition: form-data;name=\"media\"; filename=\"" + file.getName() + "\"\r\n");
//            sb.append("Content-Type:application/octet-stream\r\n\r\n");
//            OutputStream out = new DataOutputStream(conn.getOutputStream());
//            // 输出表头
//            out.write(sb.toString().getBytes("UTF-8"));
//            // 文件正文部分
//            // 把文件以流的方式 推送到URL中
//            DataInputStream din = new DataInputStream(new FileInputStream(file));
//            int bytes = 0;
//            byte[] buffer = new byte[1024];
//            while ((bytes = din.read(buffer)) != -1) {
//                out.write(buffer, 0, bytes);
//            }
//            din.close();
//            // 结尾部分
//            byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("UTF-8");//定义数据最后分割线
//            out.write(foot);
//            out.flush();
//            out.close();
//            if (HttpsURLConnection.HTTP_OK == conn.getResponseCode()) {
//                StringBuffer strbuffer = null;
//                BufferedReader reader = null;
//                try {
//                    strbuffer = new StringBuffer();
//                    reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
//                    String lineString = null;
//                    while ((lineString = reader.readLine()) != null) {
//                        strbuffer.append(lineString);
//                    }
//                    result = strbuffer.toString();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                } finally {
//                    if (reader != null) {
//                        reader.close();
//                    }
//                }
//            }
//        } catch (Exception e) {
//            log.error("异常:", e);
//        }
//        log.info(result);
//        file.delete();
//        return JSONObject.parseObject(result);
//    }
//
//    @Override
//    public JSONObject createRoom(JSONObject json) {
//        String accessToken = getToken();
//        String url = CREATE_ROOM_URL.concat(accessToken);
//        ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, json, JSONObject.class);
//        return responseEntity.getBody();
//    }
//
//    @Override
//    public JSONObject shareRoom(Integer roomId) {
//        String accessToken = getToken();
//        String url = SHARE_ROOM_URL.concat(accessToken).concat("&roomId=" + roomId);
//        ResponseEntity<JSONObject> responseEntity = restTemplate.getForEntity(url, JSONObject.class);
//        return responseEntity.getBody();
//    }
//
//    @Override
//    public JSONObject deleteRoom(JSONObject json) {
//        String accessToken = getToken();
//        String url = DELETE_ROOM_URL.concat(accessToken);
//        ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, json, JSONObject.class);
//        return responseEntity.getBody();
//    }
//
//    @Override
//    public JSONObject editRoom(JSONObject json) {
//        String accessToken = getToken();
//        String url = EDIT_ROOM_URL.concat(accessToken);
//        ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, json, JSONObject.class);
//        return responseEntity.getBody();
//    }
//
//    @Override
//    public JSONObject getLiveInfo() {
//        String accessToken = getToken();
//        JSONObject json = new JSONObject();
//        json.put("start", 0);
//        json.put("limit", 1000);
//        String url = LIVE_INFO_URL.concat(accessToken);
//        ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, json, JSONObject.class);
//        return responseEntity.getBody();
//    }
//
//    @Override
//    public ApiResult<String> getActivityQrCode(Integer activityType, Integer activityId, Integer activityPostId) {
//        String accessToken = getToken();
//        String miniQrCodeUrl = getMiniQrCodeUrl(accessToken);
//        Map<String, Object> params = Maps.newHashMap();
//        params.put("width", "280");
//        params.put("scene", activityType + ";" + activityId + ";" + activityPostId);
//        if (activityType == ActivityConstant.ONLINE) {
//            params.put("page", "pages/live/info");
//        } else if (activityType == ActivityConstant.OFFLINE) {
//            params.put("page", "pages/act/info");
//        }
//        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
//        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(params, headers);
//        ResponseEntity<byte[]> responseEntity = restTemplate.postForEntity(miniQrCodeUrl, requestEntity, byte[].class);
//        byte[] bytes = responseEntity.getBody();
//        return ApiResult.success(fileService.upload("jpg", IoUtil.toStream(bytes)));
//    }
//
//    @Override
//    public ApiResult<String> getPublicQrCode(Integer userId) {
//        String accessToken = getAccessToken();
//        if (accessToken == null) {
//            return new ApiResult<>(ApiCode.WX_ERROR_MSG.getCode(), "accessToken获取失败", null);
//        }
//        System.out.println(accessToken);
//        String qrCodeUrl = getPublicQrCodeUrl(accessToken);
//        JSONObject json1 = new JSONObject();
//        if (userId == null) {
//            json1.put("scene_str", "null");
//        } else {
//            json1.put("scene_str", "userId:" + userId);
//        }
//        JSONObject json2 = new JSONObject();
//        json2.put("scene", json1);
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("action_name", "QR_LIMIT_STR_SCENE");
//        jsonObject.put("action_info", json2);
//        ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(qrCodeUrl, jsonObject, JSONObject.class);
//        System.out.println(responseEntity);
//        String ticket = Objects.requireNonNull(responseEntity.getBody()).getString("ticket");
//        String url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=";
//        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
//        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(headers);
//        ResponseEntity<byte[]> forEntity = restTemplate.getForEntity(url.concat(ticket), byte[].class, requestEntity);
//        byte[] bytes = forEntity.getBody();
//        return ApiResult.success(fileService.upload("jpg", IoUtil.toStream(bytes)));
//    }
//
//    @Override
//    public JSONObject uploadNews(String mediaId, String title, String content) {
//
//        String accessToken = getAccessToken();
//        String url = UPLOAD_NEWS_URL.concat(accessToken);
//        JSONObject json = new JSONObject();
//        json.put("thumb_media_id", mediaId);
//        json.put("title", title);
//        json.put("content", content);
//        List<JSONObject> list = new ArrayList<>();
//        list.add(json);
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("articles", list);
//        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, jsonObject, String.class);
//        String result = responseEntity.getBody();
//        return JSONObject.parseObject(result);
//    }
//
//
//    @Override
//    public JSONObject uploadimg(String stringUrl) {
//        File file = imageUtil.getFileFromUrl(stringUrl);
//        String accessToken = getAccessToken();
//        String urlString = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=".concat(accessToken);
//        String result = null;
//        try {
//            URL url = new URL(urlString);
//            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
//            conn.setRequestMethod("POST");
//            conn.setDoInput(true);
//            conn.setDoOutput(true);
//            conn.setUseCaches(false);
//            conn.setRequestProperty("Connection", "Keep-Alive");
//            conn.setRequestProperty("Charset", "UTF-8");
//            // 设置边界
//            String BOUNDARY = "----------" + System.currentTimeMillis();
//            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
//            // 请求正文信息
//            // 第一部分
//            StringBuilder sb = new StringBuilder();
//            // 必须多两条道
//            sb.append("--");
//            sb.append(BOUNDARY);
//            sb.append("\r\n");
//            sb.append("Content-Disposition: form-data;name=\"media\"; filename=\"" + file.getName() + "\"\r\n");
//            sb.append("Content-Type:application/octet-stream\r\n\r\n");
//            OutputStream out = new DataOutputStream(conn.getOutputStream());
//            // 输出表头
//            out.write(sb.toString().getBytes("UTF-8"));
//            // 文件正文部分
//            // 把文件以流的方式 推送到URL中
//            DataInputStream din = new DataInputStream(new FileInputStream(file));
//            int bytes = 0;
//            byte[] buffer = new byte[1024];
//            while ((bytes = din.read(buffer)) != -1) {
//                out.write(buffer, 0, bytes);
//            }
//            din.close();
//            // 结尾部分
//            byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("UTF-8");//定义数据最后分割线
//            out.write(foot);
//            out.flush();
//            out.close();
//            if (HttpsURLConnection.HTTP_OK == conn.getResponseCode()) {
//                StringBuffer strbuffer = null;
//                BufferedReader reader = null;
//                try {
//                    strbuffer = new StringBuffer();
//                    reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
//                    String lineString = null;
//                    while ((lineString = reader.readLine()) != null) {
//                        strbuffer.append(lineString);
//                    }
//                    result = strbuffer.toString();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                } finally {
//                    if (reader != null) {
//                        reader.close();
//                    }
//                }
//            }
//        } catch (Exception e) {
//            log.error("异常:", e);
//        }
//        log.info(result);
//        file.delete();
//        return JSONObject.parseObject(result);
//    }
//
//    @Override
//    public String getMiniQrCode(String openId) {
//        String accessToken = getToken();
//        String miniQrCodeUrl = getMiniQrCodeUrl(accessToken);
//        Map<String, Object> params = Maps.newHashMap();
//        params.put("width", "280");
//        params.put("scene", openId);
//        params.put("page", "pages/home/home");
//        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
//        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(params, headers);
//        ResponseEntity<byte[]> responseEntity = restTemplate.postForEntity(miniQrCodeUrl, requestEntity, byte[].class);
//        byte[] bytes = responseEntity.getBody();
//        return fileService.upload("jpg", IoUtil.toStream(bytes));
//    }
//
//    @Override
//    public ApiResult<String> getSessionKey(String code) {
//        String url = GET_SESSION_KEY_URL.concat("appid=" + coolguaConfig.getMini().getAppId()).concat("&secret=" + coolguaConfig.getMini().getAppSecret()).concat("&js_code=" + code).concat("&grant_type=authorization_code");
//        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
//        String result = responseEntity.getBody();
//        JSONObject jsonObject = JSONObject.parseObject(result);
//        log.info(jsonObject.toJSONString());
//        if (jsonObject.getIntValue("errcode") != 0) {
//            log.error(jsonObject.getString("errmsg"));
//            return new ApiResult<>(ApiCode.SYSTEM_FAIL.getCode(), "SessionKey获取失败", null);
//        }
//        String sessionKey = jsonObject.getString("session_key");
//        log.info("sessionKey:" + sessionKey);
//        String unionId = jsonObject.getString("unionid");
//        log.info("unionId:" + unionId);
//        QueryWrapper<User> qw = new QueryWrapper<>();
//        qw.eq("wx_union_id", unionId).last("limit 1");
//        User user = userService.getOne(qw);
//        if (user != null) {
//            user.setWxSessionKey(sessionKey);
//            userService.updateById(user);
//        }
//        return ApiResult.success(sessionKey);
//    }
//}
